package com.ayf.payment.game.api.service.payment;

import com.ayf.payment.game.api.dto.OrderAndMerchantDTO;
import com.ayf.payment.game.api.dto.platform.MerchantPaymentProductDTO;
import com.ayf.payment.game.api.dto.platform.PaymentChannelDTO;
import com.ayf.payment.game.api.entity.Order;
import com.ayf.payment.game.api.entity.Partition;
import com.ayf.payment.game.api.exception.NullSetException;
import com.ayf.payment.game.api.utils.BigDecimalUtil;
import com.ayf.payment.game.api.utils.Md5Utils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

@Service
public class QiYiPaymentService extends IPaymentService {


    @Override
    public Map<String, Object> paymentUtil(Order order, Partition partition, String orderCreateStr, String traceId, String redirectUrl) {
        LogPortal.info("{} 奇易支付开始创建订单", traceId);
        Map<String, Object> map = new HashMap<>();
        MerchantPaymentProductDTO merchantPaymentProductDTO = systemInitialization.productDTO(order.getPayTypeId());
        PaymentChannelDTO paymentChannelDTO = systemInitialization.channelDTO(merchantPaymentProductDTO.getcId());
        String KeyValue = paymentChannelDTO.getChannelKey();
        String parter = paymentChannelDTO.getAccountNumber();
        String AuthorizationURL = paymentChannelDTO.getPaymentUrl();
        String notifyUrl = paymentChannelDTO.getReturnUrl();
        if (!AuthorizationURL.endsWith("/")) {
            AuthorizationURL = AuthorizationURL.concat("/");
        }
        AuthorizationURL = AuthorizationURL.concat("main/gateway?");

        if (!notifyUrl.endsWith("/")) {
            notifyUrl = notifyUrl.concat("/");
        }

        BigDecimal actualOrderAmt = getActualOrderAmt(order.getAmount(),paymentChannelDTO.getId(),partition.getMerchantId());
        Map<String, Object> dicMap = new HashMap<>();
        dicMap.put("user_id", parter);
        dicMap.put("order_id", order.getMerchantOrderNo());
        dicMap.put("pro_code", getPayCode(merchantPaymentProductDTO.getBusinessCode()));
        dicMap.put("total_fee",BigDecimalUtil.yuanToFen(actualOrderAmt));
        dicMap.put("charset", "UTF-8");
        dicMap.put("pay_type", "1");
        dicMap.put("notify_url", notifyUrl.concat("gameapip/v/qiyi/pay/notify"));
        dicMap.put("return_url", notifyUrl.concat("gameapip/v/qiyi/pay/returns"));
        dicMap.put("attach", redirectUrl);
        dicMap.put("agency_id", "2155");
        Map<String, Object> sortByKey = sortByKey(dicMap);
        Set<String> keySet = sortByKey.keySet();
        StringBuilder str = new StringBuilder();
        for (String key : keySet) {
            str.append(key).append("=").append(sortByKey.get(key)).append("&");
        }
        String str2 = str.substring(0, str.length() - 1);
        String str3 = str2 + KeyValue;
        String sign = Md5Utils.md5LowerCase(str3);
        str2 = str2 + "&sign=" + sign;
        LogPortal.info("{} 奇易支付 商户ID[{}] 商户订单号[{}] 下单请求URL[{}]参数[{}]", traceId, order.getMerchantId(),order.getMerchantOrderNo(), AuthorizationURL, str2);
        order.setRandomAmt(BigDecimal.ZERO);
        order.setOrderNo("");
        order.setPayChannleName(paymentChannelDTO.getName());
        order.setPayChannleId(paymentChannelDTO.getId());
        order.setPayTypeId(merchantPaymentProductDTO.getProductId());
        order.setPayTypeName(merchantPaymentProductDTO.getProductName());
        order.setMerchantIncome(BigDecimal.ZERO);
        order.setPlatformIncome(BigDecimal.ZERO);
        order.setFee(BigDecimal.ZERO);
        order.setChannelIncome(BigDecimal.ZERO);
        orderMapper.insertSelective(order);
        map.put("code", "003");
        map.put("RedirectUrl", AuthorizationURL + str2);
        return map;
    }


    private static Map<String, Object> sortByKey(Map<String, Object> map) {
        Map<String, Object> treeMap = new TreeMap<>(String::compareTo);
        treeMap.putAll(map);
        return treeMap;
    }

    @Override
    public void queryPayOrder(OrderAndMerchantDTO dto, String traceId) {

    }

    private String getPayCode(String code) {
        if ("ALIPAY".equals(code)) {
            return "alipay";
        } else if ("ANTCREDITPAY".equals(code)) {
            return "hbpay";
        } else if ("WECHAT".equals(code)) {
            return "wechat";
        } else {
            throw new NullSetException("该通道不支持充值，请更换其他通道充值！");
        }
    }

}
